package com.aura.lyngen.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.aura.lyngen.exception.BusinessException;
import com.aura.lyngen.exception.ErrorCode;
import com.aura.lyngen.model.dto.user.UserQueryRequest;
import com.aura.lyngen.model.enums.UserRoleEnum;
import com.aura.lyngen.model.vo.LoginUserVO;
import com.aura.lyngen.model.vo.UserVO;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.aura.lyngen.model.entity.User;
import com.aura.lyngen.mapper.UserMapper;
import com.aura.lyngen.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.aura.lyngen.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 服务层实现。
 *
 * @author ZJX
 * @since 2025-08-22 13:57:58
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
//        1. 校验参数
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL, "用户注册参数不能为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.USER_ACCOUNT_TOO_SHORT, "用户账号过短，至少4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.USER_PASSWORD_TOO_SHORT, "密码过短，至少8位");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.USER_PASSWORD_MISMATCH, "两次输入的密码不一致");
        }
//        2. 查询用户是否存在
        long account = this.mapper.selectCountByQuery(QueryWrapper.create().eq("user_account", userAccount));
        if (account > 0) {
            throw new BusinessException(ErrorCode.USER_ALREADY_EXISTS, "用户已存在");
        }
//        3. 加密密码
        String encryptPassword = this.encryptPassword(userPassword);
//        4. 创建用户，存储在数据库
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        // 生成随机数并拼接成用户名
        String userName = "无名氏" + (int) (Math.random() * 10000) + "号";
        // 设置用户名
        user.setUserName(userName);
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saved = save(user);
        if (!saved) {
            throw new BusinessException(ErrorCode.USER_REGISTRATION_FAILED, "用户注册失败, 请重试");
        }
        return user.getId();
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
//        1. 校验参数
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL, "登录参数不能为空");
        }

//        2. 加密
        String encryptPassword = this.encryptPassword(userPassword);

//        3. 判断用户是否存在
        User user = this.mapper.selectOneByQuery(QueryWrapper.create().eq("user_account", userAccount).eq("user_password", encryptPassword));
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGIN_FAILED, "用户名或密码错误");
        }
//        4. 记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);

        return getLoginUserVO(user);
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
//        1. 判断是否登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
//        2. 从数据库获取当前信息
        long userId = user.getId();
        user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
//        先判断是否登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
//        移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 根据用户查询请求构建查询条件包装器
     *
     * @param userQueryRequest 用户查询请求对象，包含查询条件
     * @return QueryWrapper 构建好的查询条件包装器，用于数据库查询
     * @throws BusinessException 当请求参数为空时抛出业务异常
     */
    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        // 参数校验，如果请求参数为空则抛出异常
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        // 从请求对象中获取查询条件
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        // 构建查询条件
        return QueryWrapper.create()
                // 精确匹配ID
                .eq("id", id)
                // 精确匹配用户角色
                .eq("user_role", userRole)
                // 模糊匹配用户账号
                .like("user_account", userAccount)
                // 模糊匹配用户名
                .like("user_name", userName)
                // 模糊匹配用户简介
                .like("user_profile", userProfile)
                // 排序处理，根据sortField排序，sortOrder为"ascend"时升序排序
                .orderBy(sortField, "ascend".equals(sortOrder));
    }


    @Override
    public String encryptPassword(String userPassword) {
//        盐值加密
        final String SALT = "lyngen";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }


}
